<template>
  <div>
    <div class="top-operate-default mar-b-20">
      <div class="search-item">
        <label>搜索：</label>
        <el-select v-model="keywordType" placeholder="请选择">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
        <el-input v-model="keyword" @keyup.enter.native="handleSearch" placeholder="店主昵称/姓名/手机号/所属招募员"
          style="width: 300px"></el-input>
        <label class="mar-l-20">注册时间：</label>
        <el-date-picker v-model="starEndTime" type="daterange" unlink-panels range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
        <label class="mar-l-20">店主等级：</label>
        <el-select v-model="memberGradeId" placeholder="是否实名" class="pad-l-10" style="width: 140px">
          <el-option label="全部" value=""></el-option>
          <el-option v-for="(item, index) in gradeList" :key="index" :label="item.gradeName"
            :value="item.memberGradeId">
          </el-option>
        </el-select>
        <label class="mar-l-20">实名状态：</label>
        <el-select v-model="authFlagType" placeholder="是否实名" class="pad-l-10" style="width: 140px">
          <el-option label="全部" value=""></el-option>
          <el-option v-for="(value, key) in authFlagList" :key="value" :label="value" :value="key">
          </el-option>
        </el-select>
        <label class="mar-l-20">批发权限：</label>
        <el-select v-model="wholesaleAuthority" placeholder="批发权限" clearable class="pad-l-10" style="width: 140px">
          <el-option label="开启" value="1"></el-option>
          <el-option label="关闭" value="0"></el-option>
        </el-select>
        <label class="mar-l-20">主播权限：</label>
        <el-select v-model="anchorAuthority" placeholder="主播权限" clearable class="pad-l-10" style="width: 140px">
          <el-option label="开启" value="1"></el-option>
          <el-option label="关闭" value="0"></el-option>
        </el-select>
        <el-button-group>
          <el-button type="primary" @click="handleSearch" style="margin-left: 10px">查询</el-button>
          <el-button plain="" @click="resetSearch">重置</el-button>
        </el-button-group>
      </div>
    </div>
    <!-- 操作区域 -->
    <div class="tabs-box mar-t-15">
      <el-tabs type="card" v-model="activeName" class="member-list-tab" @tab-click="handleClick">
        <el-tab-pane :label="allName" name="0"></el-tab-pane>
        <el-tab-pane :label="enterpriseName" name="2"></el-tab-pane>
        <el-tab-pane :label="recruiterName" name="1"></el-tab-pane>
      </el-tabs>
    </div>
    <!-- 全选、操作 -->
    <div>
      <div class="pad-t-15 pad-b-15 font-14 v-align-c">
        <el-checkbox class="mar-l-14 mar-r-0" v-model="allChecked" @change="selectAll"><span
            class="mar-l-20">当页全选</span></el-checkbox>
        <span class="pad-l-4 pad-r-4">|</span>
        <div class="width-80">已选{{multipleSelection.length}}项</div>
        <el-popover v-if="enterpriseConfig.memberPriceAuthority == 1" placement="bottom" width="180" trigger="click"
          v-model="visibleMemberFlag">
          <el-form class="pad-t-10">
            <el-form-item>
              <el-radio v-model="memberFlag" label="1">开启会员身份</el-radio>
              <el-radio v-model="memberFlag" label="0" class="mar-t-10">关闭会员身份</el-radio>
            </el-form-item>
          </el-form>
          <div>
            <el-button size="mini" @click="visibleMemberFlag = false">取消</el-button>
            <el-button type="primary" size="mini" @click="batchUpdateMember('1')">确定</el-button>
          </div>
          <el-button slot="reference" class="batch-btn mar-r-10" @click="setMemberFlag">设置会员身份</el-button>
        </el-popover>
        <!-- <el-button class="batch-btn mar-l-10" @click="batchUpdateMember('3')" v-if="enterpriseConfig.wholesaleAuthority === 1">开启批发权限</el-button> -->
        <el-button class="batch-btn" @click="gradeClick">设置店主等级</el-button>
        <el-button class="batch-btn" @click="openCustomImport">导入自定义信息</el-button>
        <!--<el-button @click="distributionSetup" >基本设置</el-button>-->
      </div>
    </div>
    <!-- 内容列表 -->
    <div class="table-container">
      <el-table ref="multipleTable" :data="memberList" @sort-change="sortChange"
        @selection-change="handleSelectionChange" v-loading="listLoading" element-loading-text="加载中" style="width: 100%"
        header-cell-class-name="default-header" row-class-name="default-row">
        <el-table-column width="55px" type="selection"></el-table-column>
        <el-table-column width="300px" label="微客" prop="userInfo" fixed="left">
          <template slot-scope="scope">
            <div @click="handleUpdate(scope.row)" class="flex v-align-c cursor-p">
              <div v-if="enterpriseConfig.memberPriceAuthority == 1" class="vip-icon-box"><img
                  v-if="scope.row.memberFlag == 1" :src="vipIcon" alt=""></div>
              <el-tooltip class="item" effect="dark" :content="'微客ID:' + scope.row.memberId" placement="top-start">
                <label><img :src="scope.row.avatar" class="user-avatar cursor-p" v-if="scope.row.avatar"></label>
              </el-tooltip>
              <div class="font-14 pad-l-10 height-59 line-h-14">
                <div><span class="font-color-9">昵称：</span>{{scope.row.nickname}}</div>
                <div><span class="font-color-9">姓名：</span>{{scope.row.realName}}</div>
                <div><span class="font-color-9">手机：</span>{{scope.row.phone}}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="240px" label="来源" prop="nature">
          <template slot-scope="scope">
            <div v-if="scope.row.nature == 1">
              <span>招募员招募</span><br />
              <span class="font-color-9">姓名：</span>{{scope.row.customerRealname}}<br />
              <span class="font-color-9">手机：</span>{{scope.row.customerPhone}}
            </div>
            <div v-if="scope.row.nature == 2">
              <span>总部招募</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="240px" label="店主等级" prop="gradeName"></el-table-column>
        <el-table-column width="240px" label="注册时间" prop="premiumTime">
        </el-table-column>
        <el-table-column width="200px" label="批发权限/主播权限">
          <template slot-scope="scope">
            <span>{{ scope.row.wholesaleAuthority == 1 ? '开启' : '关闭' }}/{{ scope.row.anchorAuthority == 1 ? '开启' : '关闭' }}</span>
          </template>
        </el-table-column>
        <el-table-column width="200px" label="授信额度">
          <template slot-scope="scope">
            <div class="line-h-14" v-if="scope.row.creditType === 2">
              <div><span class="font-blue"> {{ creditTypeList[scope.row.creditType] }}</span></div>
              <div><span class="font-color-9">最高额度：</span>￥{{scope.row.highestQuota ? scope.row.highestQuota : '0.00'}}
              </div>
              <div><span class="font-color-9">已用额度：</span>￥{{scope.row.usedQuota ? scope.row.usedQuota : '0.00'}}</div>
              <div><span
                  class="font-color-9">剩余额度：</span>￥{{scope.row.highestQuota ? scope.row.highestQuota - (scope.row.usedQuota ? scope.row.usedQuota : '0.00') : '0.00' }}
              </div>
            </div>
            <div class="line-h-14" v-else-if="scope.row.creditType === 1 || scope.row.creditType === 3">
              <div><span class="font-blue"> {{ creditTypeList[scope.row.creditType] }}</span></div>
            </div>
            <div class="line-h-14" v-else>
              <div><span class="font-red">未选择授信类型</span></div>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="200px" label="累计成交">
          <template slot-scope="scope">
            <div class="line-h-14">
              <div><span class="font-color-9">订单：</span>{{scope.row.orderNum}}</div>
              <div><span class="font-color-9">金额：</span>{{scope.row.orderPrice}}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="200px" label="备注" prop="remarkName">
        </el-table-column>
        <el-table-column min-width="200px" label="操作" align="right" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="medium" @click="handleUpdate(scope.row)">查看</el-button>
            <el-button type="text" size="medium" @click="setHighestQuotaShow(scope.row)">设置授信额度</el-button>
            <el-popover placement="bottom" width="100" trigger="hover" popper-class="popover-class">
              <el-button class="mar-l-10" type="text" size="medium" slot="reference">更多</el-button>
              <div>
                <el-button type="text" size="medium" @click="editRemark(scope.row)">备注</el-button>
                <el-button type="text" size="medium" @click="updateWxaCode(scope.row)">刷新小程序码</el-button>
              </div>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 列表分页 -->
    <div class="pagination">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="memberListQuery.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="memberListQuery.size"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!-- 添加内部微客弹窗 -->
    <el-dialog title="" :visible.sync="financeVisible" :close-on-press-escape="true" width="400px">
      <div>
        <img :src="enterpriseWxaCode" style="width: 400px">
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="financeVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 分销设置弹窗 -->
    <el-dialog title="" :visible.sync="distributionSetupBoolean" :close-on-press-escape="true" width="600px"
      :show-close="false">
      <el-tabs v-model="basicStatus" @tab-click="handleClickBasic">
        <el-tab-pane label="分销设置" name="0"></el-tab-pane>
        <el-tab-pane label="批发设置" name="1"></el-tab-pane>
      </el-tabs>
      <template v-if="basicStatus === '0'">
        <div style="background-color: #D9EDF7; color: #36A3F7; border:1px solid #C5DCE7; margin-left: 2%; width: 96%">
          <span style="margin-top: 20px">温馨提示：</span><br />
          <span>1、开启：</span><br />
          <span style="margin-left: 10px">a.企业微客可申请分销其他企业的商品，分销成功后您将获得相应的佣金。</span><br />
          <span style="margin-left: 10px">b.企业微客无法分销与您本企业主营类目一致的商品。</span><br />
          <span>2、关闭：</span><br />
          <span style="margin-left: 10px">a.企业微客只能分销您的商品。</span><br />
          <span
            style="margin-left: 10px">b.如果在您之前开启的过程中企业微客有申请分销其他企业，并且通过后将企业商品上架到店铺中售卖，则在您关闭后上架的商品将会保留在您的企业微客店铺中。</span><br />
        </div>
        <div style="margin-left: 20px; margin-top: 20px">
          <el-switch v-model="distributionType" active-color="#13ce66" inactive-color="#ff4949">
          </el-switch><span style="font-size: 20px; margin-left: 10px">开关</span>
          <span style="color: red" v-if="distributionType === false">(已关闭)</span>
          <span style="color: deepskyblue" v-if="distributionType === true">(已开启)</span>
        </div>
      </template>
      <template v-if="basicStatus === '1'">
        <div style="background-color: #D9EDF7; color: #36A3F7; border:1px solid #C5DCE7; margin-left: 2%; width: 96%">
          <span style="margin-top: 20px">温馨提示：</span><br />
          <span style="margin-left: 10px">1、开启：成为企业内部、外部微客后将自动获得批发权限。</span><br />
          <span style="margin-left: 10px">2、关闭：成为企业内部、外部微客后将没有批发权限。</span><br />
        </div>
        <div style="margin-left: 20px; margin-top: 20px">
          <el-switch v-model="memberWholesaleAuthority" active-color="#13ce66" inactive-color="#ff4949">
          </el-switch><span style="font-size: 20px; margin-left: 10px">开关</span>
          <span style="color: red" v-if="memberWholesaleAuthority === false">(已关闭)</span>
          <span style="color: deepskyblue" v-if="memberWholesaleAuthority === true">(已开启)</span>
        </div>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button @click="saveDistributionType" type="primary">保存设置</el-button>
        <el-button @click="distributionSetupBoolean = false">关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="设置账号" :visible.sync="setSubUserVisible" :close-on-press-escape="true" width="550px">
      <el-form :model="subUser" label-width="150px" :rules="rules" ref="subUser">
        <el-form-item label="昵称" prop="nickname">
          <div>{{subUser.nickname}}</div>
        </el-form-item>
        <el-form-item label="操作员姓名" prop="username">
          <div>
            <el-input v-model="subUser.username" placeholder="请输入操作员姓名" style="width: 300px"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="登录手机号" prop="phone">
          <div>
            <el-input v-model="subUser.phone" type="tel" placeholder="请输入手机号" maxlength="11"
              oninput="this.value=this.value.replace(/^[0,2,3,4,5,6,7,8,9]*$/gi,'')"
              onkeyup="this.value=this.value.replace(/\D/g,'')" style="width: 300px"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="所属角色" prop="subRoleId">
          <div>
            <el-select v-model="subUser.subRoleId" placeholder="请选择">
              <el-option v-for="(item, index) in subRoleList" :key="item.subRoleId" :index="index" :label="item.name"
                :value="item.subRoleId" />
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio v-model="subUser.status" label="1">启用</el-radio>
          <el-radio v-model="subUser.status" label="0">禁用</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setSubUserVisible = false">取消</el-button>
        <el-button type="primary" @click="doBindSubUser">保存</el-button>
      </div>
    </el-dialog>

    <!-- 拒绝通过 -->
    <el-dialog title="备注" :visible.sync="remarkVisible" :close-on-press-escape="true" width="460px">
      <div style="padding:20px;">
        <el-input type="textarea" :rows="6" placeholder="请输入内容" v-model="memberRemark.remarkName">
        </el-input>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRemark">确认</el-button>
        <el-button @click="remarkVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!--设置店主等级-->
    <el-dialog title="设置店主等级" :visible.sync="gradeVisible" :close-on-press-escape="true" width="460px">
      <div style="text-align: center">
        <span style="font-size: 16px">店主等级：</span>
        <el-select v-model="gradeId" placeholder="请选择店主等级" class="pad-l-10" style="width: 200px">
          <el-option v-for="(item, index) in gradeList" :key="index" :label="item.gradeName"
            :value="item.memberGradeId">
          </el-option>
        </el-select>
      </div>
      <div slot="footer" class="dialog-footer pad-t-20">
        <el-button type="primary" @click="saveGrade">保存</el-button>
        <el-button @click="gradeVisible = false">取消</el-button>
      </div>
    </el-dialog>
    <!-- 导入自定义信息 -->
    <el-dialog width="600px" v-el-drag-dialog title="导入自定义信息" :visible.sync="customImportVisible">
      <custom-import :showFlag="customImportVisible" moduleCode="1001" @close="closeCustomImport"></custom-import>
    </el-dialog>

    <!--设置授信额度-->
    <el-dialog title="设置授信额度" :visible.sync="setHighestQuotaVisible" :close-on-press-escape="true" width="460px">
      <div style="margin-left: 55px">
        <span style="font-size: 16px">授信类型：</span>
        <el-radio v-model="setHighestQuotaInfo.creditType" label="1" @change="creditTypeChange">即时付款</el-radio>
      </div>
      <div style="margin-left: 140px; margin-top: 10px">
        <el-radio v-model="setHighestQuotaInfo.creditType" label="2" @change="creditTypeChange">额度授信</el-radio>
        <el-input style="width: 250px; margin-top: 10px" placeholder="请输入最高额度"
          v-model="setHighestQuotaInfo.highestQuota" :disabled="highestQuotaShow"
          @keyup.native="setHighestQuotaInfo.highestQuota = checkInputNum(setHighestQuotaInfo.highestQuota)"
          size="mini"><template slot="append">元</template></el-input>
        <div class="config-tip font-12 font-color-9">
          最高额度必须大于等于0,
          <el-tooltip placement="top">
            <div slot="content">
              当前最高额度: ￥{{ setHighestQuotaInfo.highestQuota ? setHighestQuotaInfo.highestQuota : '0.00' }}<br />
              已使用额度: ￥{{ setHighestQuotaInfo.usedQuota ? setHighestQuotaInfo.usedQuota : '0.00' }}<br />
              当前可用额度:
              ￥{{ setHighestQuotaInfo.highestQuota && setHighestQuotaInfo.usedQuota ? setHighestQuotaInfo.highestQuota - setHighestQuotaInfo.usedQuota : '0.00' }}<br />
            </div>
            <i class="el-icon-info">查看当前额度</i>
          </el-tooltip>
        </div>
      </div>
      <div style="margin-left: 140px; margin-top: 10px">
        <el-radio v-model="setHighestQuotaInfo.creditType" label="3" @change="creditTypeChange">不限额度</el-radio>
        <div class="config-tip font-12 font-color-9">选用不限额度可能导致不可控的分销商欠款，谨慎使用！</div>
      </div>
      <div slot="footer" class="dialog-footer pad-t-20">
        <el-button type="primary" @click="setHighestQuotaType">保存</el-button>
        <el-button @click="setHighestQuotaVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    pagingEnterpriseShop,
    enableDisable,
    bacthUpdate,
    bacthUpdateAuthority,
    doBindSubUser,
    saveMemberRemark,
    getBindSubUser,
    countMyMember,
    saveMemberGradeBatch,
    doSetHighestQuota
  } from '@/api/user/member'
  import {
    doNatureInWxaCode,
    updateDistributionType,
    getEnterprise
  } from '@/api/user/enterprise'
  import {
    getByEnterpriseId
  } from '@/api/user/enterprise'
  import {
    listMemberGrade
  } from '@/api/user/memberGrade'
  import {
    refreshMemberWxaCode
  } from '@/api/common/common'

  import elDragDialog from '@/directive/el-dragDialog' // base on element-ui
  import store from '@/store'
  import {
    listEnterpeiseRole
  } from '@/api/system/role'
  import customImport from '@/views/system/custom-form/components/custom-import'
  import vipIcon from '@/assets/images/vip-icon.png'
  import {
    getDictByGroupName
  } from '@/api/common/common'

  export default {
    components: {
      customImport
    },
    directives: {
      // 拖动窗口
      elDragDialog
    },
    props: {
      memberId: {
        type: String
      }
    },
    data() {
      return {
        basicStatus: '0',
        memberList: [],
        gradeList: [],
        memberGradeId: '',
        gradeId: '',
        starEndTime: [],
        th_memberList: [],
        authFlagList: [],
        natureList: [],
        creditTypeList: [],
        authFlagType: '',
        activeName: '0',
        total: null,
        distributionType: '',
        memberWholesaleAuthority: '',
        distributionSetupBoolean: false,
        setSubUserVisible: false,
        gradeVisible: false,
        listLoading: true,
        financeVisible: false,
        remarkVisible: false,
        multipleSelection: [],
        memberListQuery: {
          currentPage: 1,
          size: 10
        },
        member: {
          memberId: '',
          nickname: '',
          realName: '',
          nature: '',
          memberGrade: '',
          labelName: '',
          phone: '',
          taskRegisteredTime: '',
          authFlag: '',
          taskStatus: '',
          delFlag: '',
          enterpriseId: '',
          status: '0'
        },
        wholesaleAuthority: '',
        anchorAuthority: '',
        keywordType: 'nickname',
        keyword: '',
        options: [{
          value: 'nickname',
          label: '店主昵称'
        }, {
          value: 'realName',
          label: '姓名'
        }, {
          value: 'phone',
          label: '手机号'
        }, {
          value: 'recruiterName',
          label: '招募员姓名'
        }, {
          value: 'recruiterPhone',
          label: '招募员电话'
        }],
        enterpriseConfig: {
          wholesaleAuthority: 0
        },
        subUser: {},
        subRoleList: [],
        rules: {
          phone: [{
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          }],
          subRoleId: [{
            required: true,
            message: '请选择角色',
            trigger: 'blur'
          }],
          username: [{
            required: true,
            message: '请输入操作员姓名',
            trigger: 'blur'
          }]
        },
        memberAuthority: {},
        memberRemark: {
          memberRemarkId: '',
          remarkType: 1,
          remarkName: '',
          memberId: '',
          userId: this.getEnterpriseId()
        },
        setHighestQuotaInfo: {
          memberId: '',
          creditType: 1,
          highestQuota: 0,
          usedQuota: 0
        },
        enterpriseWxaCode: '',
        allName: '全部（0）',
        enterpriseName: '总部招募（0）',
        recruiterName: '招募员招募（0）',
        natureStyleMap: {
          0: 'font-yellow',
          1: 'font-blue',
          2: 'font-green'
        },
        authFlagStyleMap: {
          0: 'font-orange',
          1: 'font-green'
        },
        allChecked: false,
        visibleMemberFlag: false,
        memberFlag: '0',
        customImportVisible: false,
        setHighestQuotaVisible: false,
        vipIcon,
        highestQuotaShow: true
      }
    },
    // 过滤器
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          2: 'danger'
        }
        return statusMap[status]
      }
    },
    // 初始化页面
    created() {
      this.queryParams = this.getCurrentPage().query
      if (this.queryParams && this.queryParams.recruiterId) {
        this.memberListQuery.recruiterId = this.queryParams.recruiterId.toString()
      }
      this.initConfig()
      this.listMemberGrade()
      this.initMemberList()
      this.listEnterpeiseRole()
    },
    methods: {
      gradeClick() {
        if (this.multipleSelection.length > 0) {
          this.gradeVisible = true
          this.gradeId = ''
        } else {
          this.$message.error('请选择要操作的数据')
        }
      },
      saveGrade() {
        if (!this.gradeId) {
          this.$message.error('请选择店主等级')
          return
        }
        const memberIds = []
        this.multipleSelection.forEach((item) => {
          memberIds.push(item.memberId)
        })
        saveMemberGradeBatch(memberIds.join(','), this.gradeId).then(response => {
          if (response.isError) return
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.gradeVisible = false
          this.initMemberList()
        })
      },
      listMemberGrade() {
        listMemberGrade(this.getEnterpriseId()).then(response => {
          if (response.isError) return
          this.gradeList = response.data
        })
      },
      initCountMyMember(query) {
        countMyMember(query).then(response => {
          if (response.isError) return
          this.allName = '全部（' + Math.floor(response.data.allNum) + '）'
          this.enterpriseName = '总部招募（' + Math.floor(response.data.enterpriseNum) + '）'
          this.recruiterName = '招募员招募（' + Math.floor(response.data.recruiterNum) + '）'
        })
      },
      initConfig() {
        getByEnterpriseId(this.getEnterpriseId()).then(response => {
          if (response.isError) return
          this.enterpriseConfig = response.data
        })
      },
      listEnterpeiseRole() {
        listEnterpeiseRole({
          enterpriseId: this.getEnterpriseId(),
          memberFlag: 1
        }).then(response => {
          if (response.isError) return
          this.subRoleList = response.data
        })
      },
      initMemberList() {
        this.listLoading = true
        const query = {}
        query['currentPage'] = this.memberListQuery.currentPage
        query['size'] = this.memberListQuery.size
        query['enterpriseId'] = this.getEnterpriseId()
        query['recruiterId'] = this.memberListQuery.recruiterId ? this.memberListQuery.recruiterId : ''
        query['nature'] = this.activeName === '0' ? '' : this.activeName
        query['veekrayStatus'] = 1
        query['authFlag'] = this.authFlagType
        query['wholesaleAuthority'] = this.wholesaleAuthority
        query['anchorAuthority'] = this.anchorAuthority
        query['memberGradeId'] = this.memberGradeId
        query[this.keywordType] = this.keyword
        if (this.starEndTime) {
          if (this.starEndTime.length > 0) {
            query['startDate'] = this.starEndTime[0]
            query['endDate'] = this.starEndTime[1]
          }
        }
        this.initCountMyMember(query)
        pagingEnterpriseShop(query).then(response => {
          if (response.isError) return
          this.memberList = response.data.records
          if (this.memberList) {
            for (let i = 0; i < this.memberList.length; i++) {
              this.memberList[i].userInfo = {}
              this.memberList[i].userInfo.avatar = this.memberList[i].avatar
              this.memberList[i].userInfo.nickname = this.memberList[i].nickname
              this.memberList[i].userInfo.realName = this.memberList[i].realName
              this.memberList[i].natureStyle = this.natureStyleMap[this.memberList[i].nature]
              this.memberList[i].authFlagStyle = this.authFlagStyleMap[this.memberList[i].authFlag]
            }
          }
          if (this.memberList != null && this.memberList.length > 0) {
            if (response.data.dict.authFlag != null) {
              this.authFlagList = response.data.dict.authFlag
            }
            if (response.data.dict.nature != null) {
              this.natureList = response.data.dict.nature
            }
            getDictByGroupName('MemberDTO.creditType').then(response => {
              this.creditTypeList = response.data.creditType
            })
          }
          this.total = response.data.total
          this.listLoading = false
        })
      },
      // 列表排序
      sortChange(data) {
        const {
          prop,
          order
        } = data
        if (prop === 'registeredTime') {
          if (order === 'ascending') {
            this.memberListQuery.asc = 'registeredTime'
            this.memberListQuery.desc = ''
          } else {
            this.memberListQuery.asc = ''
            this.memberListQuery.desc = 'registeredTime'
          }
        }
        this.initMemberList()
      },
      handleClick() {
        this.memberListQuery.currentPage = 1
        this.initMemberList()
      },
      handleClickBasic() {},
      handleSearch() {
        this.memberListQuery.currentPage = 1
        this.initMemberList()
      },
      resetSearch() {
        this.searchReset()
        this.initMemberList()
      },
      searchReset() {
        this.keywordType = 'nickname'
        this.keyword = ''
        this.memberGradeId = ''
        this.wholesaleAuthority = ''
        this.anchorAuthority = ''
        this.starEndTime = []
        this.memberListQuery = {
          currentPage: 1,
          size: 10
        }
      },
      handleSizeChange(val) {
        this.memberListQuery.size = val
        this.initMemberList()
      },
      handleCurrentChange(val) {
        this.memberListQuery.currentPage = val
        this.initMemberList()
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
        this.th_memberList = []
        if (this.multipleSelection.length === this.memberList.length) {
          this.allChecked = true
        } else {
          this.allChecked = false
        }
      },
      // 添加内部微客
      handleCreate() {
        const data = {
          enterpriseId: this.getEnterpriseId()
        }
        doNatureInWxaCode(data).then(response => {
          if (response.isError) return
          this.enterpriseWxaCode = response.data
          this.financeVisible = true
        })
      },
      // 设置账户
      bindSubUser(row) {
        getBindSubUser(row.memberId).then(response => {
          if (response.isError) return
          this.subUser = response.data
          this.subUser.status = this.subUser.status ? this.subUser.status + '' : '1'
          this.subUser.nickname = row.nickname
          this.subUser.memberId = row.memberId
          this.setSubUserVisible = true
        })
      },
      // 设置账户
      editRemark(row) {
        this.memberRemark.memberRemarkId = row.memberRemarkId
        this.memberRemark.memberId = row.memberId
        this.memberRemark.remarkName = row.remarkName
        this.memberRemark.remarkType = '4'
        this.memberRemark.userId = this.getEnterpriseId()
        this.remarkVisible = true
      },
      submitRemark() {
        saveMemberRemark(this.memberRemark).then(response => {
          if (response.isError) return
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.remarkVisible = false
          this.initMemberList()
        })
      },
      // 设置账户
      doBindSubUser() {
        this.$refs['subUser'].validate((valid) => {
          if (valid) {
            this.subUser.enterpriseId = this.getEnterpriseId()
            doBindSubUser(this.subUser).then(response => {
              if (response.isError) return
              this.$message({
                type: 'success',
                message: '成功!'
              })
              this.setSubUserVisible = false
            })
          }
        })
      },
      // 详情
      handleUpdate(row) {
        this.$router.push({
          path: '/user/member-shopkeeper/details/index',
          query: {
            memberId: row.memberId,
            enterpriseId: this.getEnterpriseId()
          }
        })
      },
      distributionSetup() {
        getEnterprise(this.getEnterpriseId()).then(response => {
          if (response.isError) return
          if (response.data.distributionType === 0) {
            this.distributionType = false
          }
          if (response.data.distributionType === 1) {
            this.distributionType = true
          }
          if (response.data.memberWholesaleAuthority === 0) {
            this.memberWholesaleAuthority = false
          }
          if (response.data.memberWholesaleAuthority === 1) {
            this.memberWholesaleAuthority = true
          }
          this.basicStatus = '0'
          this.distributionSetupBoolean = true
        })
      },
      saveDistributionType() {
        let type = 0
        if (this.distributionType === true) {
          type = 1
        }
        let memberType = 0
        if (this.memberWholesaleAuthority === true) {
          memberType = 1
        }
        const data = {
          enterpriseId: this.getEnterpriseId(),
          distributionType: type,
          memberWholesaleAuthority: memberType
        }
        updateDistributionType(data).then(response => {
          if (response.isError) return
          this.$message({
            message: '成功',
            type: 'success'
          })
          this.distributionSetupBoolean = false
        })
      },
      // 更新
      handleUpdateStatus(row, status) {
        this.resetMember()
        this.member = Object.assign(this.member, row)
        this.member.taskStatus = status
        let name = ''
        if (status === 2) {
          name = '禁用成功!'
        } else {
          name = '启用成功!'
        }
        enableDisable(this.member).then((response) => {
          if (response.isError) return
          this.$message({
            type: 'success',
            message: name
          })
          this.initMemberList()
        })
      },
      isDisabled(row) {
        // 不能锁定、删除自己
        return row.username === store.getters.username
      },
      // 重置member
      resetMember() {
        this.member = {
          memberId: '',
          nickname: '',
          realName: '',
          nature: '',
          memberGrade: '',
          labelName: '',
          phone: '',
          taskRegisteredTime: '',
          authFlag: '',
          taskStatus: '',
          delFlag: ''
        }
      },
      // 设置会员身份
      setMemberFlag() {
        if (!this.multipleSelection.length) {
          this.$message.error('请选择要操作的数据')
          setTimeout(() => {
            this.visibleMemberFlag = false
          }, 20)
          return
        }
      },
      // 批量操作
      batchUpdateMember(command) {
        if (!this.multipleSelection.length) {
          this.$message.error('请选择要操作的数据')
          return
        }
        if (command === '1') {
          this.multipleSelection.forEach((item) => {
            this.resetMember()
            this.member.memberId = item.memberId
            this.member.memberFlag = this.memberFlag
            this.th_memberList.push(this.member)
          })
          bacthUpdate(this.th_memberList).then(response => {
            if (response.isError) return
            this.visibleMemberFlag = false
            this.initMemberList()
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
          })
        } else {
          this.multipleSelection.forEach((item) => {
            this.memberAuthority = {}
            this.memberAuthority.memberId = item.memberId
            this.memberAuthority.enterpriseId = this.getEnterpriseId()
            this.memberAuthority.wholesaleAuthority = 1
            this.th_memberList.push(this.memberAuthority)
          })
          bacthUpdateAuthority(this.th_memberList).then(response => {
            if (response.isError) return
            this.initMemberList()
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
          })
        }
        this.th_memberList = []
      },
      selectAll() {
        if (this.multipleSelection.length === 0 || this.multipleSelection.length < this.memberList.length) {
          this.memberList.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      },
      // 导入自定义信息打开事件
      openCustomImport() {
        this.customImportVisible = true
      },
      // 导入自定义信息关闭事件
      closeCustomImport() {
        this.customImportVisible = false
        this.initMemberList()
      },
      // 打开设置授信额度窗口
      setHighestQuotaShow(row) {
        this.setHighestQuotaInfo.memberId = row.memberId
        this.setHighestQuotaInfo.creditType = row.creditType ? row.creditType.toString() : '1'
        this.setHighestQuotaInfo.highestQuota = row.highestQuota ? row.highestQuota : '0'
        this.setHighestQuotaInfo.usedQuota = row.usedQuota ? row.usedQuota : '0'
        this.highestQuotaShow = this.setHighestQuotaInfo.creditType === '1' || this.setHighestQuotaInfo.creditType ===
          '3'
        this.setHighestQuotaVisible = true
      },
      creditTypeChange() {
        // 授信类型 1- 即时付款 2- 额度授信 3- 不限额度
        if (this.setHighestQuotaInfo.creditType === '1' || this.setHighestQuotaInfo.creditType === '3') {
          this.highestQuotaShow = true
        } else {
          this.highestQuotaShow = false
        }
      },
      setHighestQuotaType() {
        if (this.setHighestQuotaInfo.creditType === '1') {
          this.saveHighestQuotaInfo()
          return
        }
        // 如果选择2- 额度授信,要检查highestQuota>0 新的最高额度不能低于已使用额度，请重新设置。
        if (this.setHighestQuotaInfo.creditType === '2') {
          if (!this.setHighestQuotaInfo.highestQuota) {
            this.$message.error('选择额度授信,需输入最高额度')
            return
          }
          if (Number(this.setHighestQuotaInfo.highestQuota) < Number(this.setHighestQuotaInfo.usedQuota)) {
            this.$message.error('最高额度需大于已使用额度(' + this.setHighestQuotaInfo.usedQuota + ')元')
            return
          }
          this.saveHighestQuotaInfo()
          return
        }
        // 如果选择3- 不限额度 弹出二次确认框 选用“不限额度”授信类型，可能导致不可控的分销商欠款，确定继续选用？  继续选用 取消
        if (this.setHighestQuotaInfo.creditType === '3') {
          this.$confirm('选用“不限额度”授信类型，可能导致不可控的分销商欠款，确定继续选用？', '提示', {
            confirmButtonText: '继续选用',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.saveHighestQuotaInfo()
          }).catch(() => {})
          return
        }
      },
      // 保存额度授信配置
      saveHighestQuotaInfo() {
        doSetHighestQuota(this.setHighestQuotaInfo).then(response => {
          if (response.isError) return
          this.initMemberList()
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          setTimeout(() => {
            this.setHighestQuotaVisible = false
          }, 20)
        })
      },
      updateWxaCode(row) {
        const memberId = row.memberId
        const nickname = row.nickname
        this.$confirm('确定刷新店主【' + nickname + '】个人小程序码？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          refreshMemberWxaCode(this.getEnterpriseId(), memberId).then(response => {
            if (response.isError) return
            this.msgSuccess('更新成功')
          })
        }).catch(() => {})
      }
    },
    mounted() {

    }
  }
</script>

<style lang="less" scoped>
  .user-avatar {
    width: 59px;
    height: 59px;
    display: block;
    border-radius: 50%;
  }

  .line-h-14 {
    line-height: 1.4;
  }

  .cursor-p {
    position: relative;

    .vip-icon-box {
      position: absolute;
      top: -4px;
      left: -7px;
      transform: rotate(308deg);
      z-index: 9;

      img {
        width: 20px;
      }
    }
  }
</style>
